<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * $Id: perm_user.php 187 2012-03-11 08:40:12Z leikou@163.com $
 */

/**
 * user module.
 *
 */


class Perm_user extends OA_Controller
{
    const CATAGORY = OA_CONST_CATAGORY::PERMISSION;


    public function __construct()
    {
        parent::__construct();

        $this->load->library('user_agent');
    }


    /**
     * @name 帐号列表
     * @desc 权限模块，展示所有帐号
     */
    public function user_list()
    {
        // Get department
        $query = $this->db->from('department')->order_by('displayorder')->get();

        $department_info = $query->result_array();
        $config_department = $this->config->item('department');

        // Get user
        $user_info = array();
        foreach($department_info as $info)
        {
            $department_id = $info['id'];
            $query = $this->db
                ->select('id, name')
                ->from('user')
                ->where('status', OA_CONST_USER::STATUS_NORMAL)
                ->where('department_id', $department_id)
                ->order_by('id')
                ->get();

            $user_info[$department_id] = $query->result_array();
        }

        // Get perm user
        $query = $this->db
            ->select('u.u_id AS id')
            ->from('user_role AS u')
            ->join('role AS r', 'u.r_id = r.id')
            ->where('r.catagory_id', OA_CONST_CATAGORY::PERMISSION)
            ->get();
        $perm_user_info = $query->result_array();
        $perm_user_list = array();
        foreach($perm_user_info as $info)
        {
            $perm_user_list[] = $info['id'];
        }

        $this->load->view('permission_user_list', array(
            'department_info' => $department_info,
            'user_info' => $user_info,
            'perm_user_list' => $perm_user_list,
            'preset_department' => $config_department['preset'],
        ));
    }


    /**
     * @name 添加帐号页面加载
     * @desc 权限模块，新增帐号加载页面
     */
    public function user_add_page()
    {
        // Get department
        $query = $this->db->from('department')->get();
        $department_info = $query->result_array();
        
        // Get role
        $role_where = array();
        if( ! $this->session->is_master())
        {
            $role_where = array(
                'catagory_id <>' => OA_CONST_CATAGORY::PERMISSION,
            );
        }

        $role_dict = $this->_get_role_dict($role_where);

        // Get catagory
        $catagory_dict = $this->_get_catagroy_dict();
        
        $this->load->view('permission_user_add_page', array(
            'department_info' => $department_info,
            'role_dict' => $role_dict,
            'catagory_dict' => $catagory_dict,
            'perm_catagory_id' => OA_CONST_CATAGORY::PERMISSION,
            'return_url' => $this->agent->referrer(),
            'token_name' => $this->security->get_csrf_token_name(),
            'token_hash' => $this->security->get_csrf_hash(),
        ));
    }


    /**
     * @name 添加帐号
     * @desc 权限模块，添加帐号
     * @method post
     */
    public function user_add()
    {
        //------ Check input begin -------------
        list($safe_vars) = $this->check(array(
            'name' => FC_chs('姓名')->min(2)->max(4)->required(),
			'username' => FC_str('用户名')->min(5)->max(20)->required(),
            'department_id' => FC_int('部门')->required(),
            'email' => FC_email('邮件地址')->max(64)->required(),
            'user_role' => FC_int('用户权限')->multi()->required(),
            'return_url' => FC_str('返回地址', '')->max(255),
        ));

        // Check department
        $query = $this->db
            ->from('department')
            ->where('id', $safe_vars['department_id'])
            ->get();
        if($query->num_rows() != 1)
        {
            show_error('您提交的部门不存在');
        }

        $query = $this->db
            ->from('user')
            ->where('username', $safe_vars['username'])
            ->get();
        if($query->num_rows() > 0)
        {
            show_error('用户名：' . $safe_vars['username'] . '已经存在了');
        }

        // Check user role
        list($is_valid, $error) = $this->_check_user_role($safe_vars['user_role']);
        if( ! $is_valid)
        {
            show_error($error);
        }

        //---------------- Check input end -----------------

        $current_dateline = time();

        $this->db->trans_start();
        
        $this->db->insert('user', array(
            'username' => $safe_vars['username'],
            'name' => $safe_vars['name'],
            'email' => $safe_vars['email'],
            'department_id' => $safe_vars['department_id'],
            'status' => OA_CONST_USER::STATUS_NORMAL,
            'dateline' => $current_dateline,
        ));
        $u_id = $this->db->insert_id();

        $insert_data = array();
        foreach($safe_vars['user_role'] as $r_id)
        {
            $insert_data[] = array(
                'u_id' => $u_id,
                'r_id' => $r_id,
            );
        }
        $this->db->insert_batch('user_role', $insert_data);

        // Cretate active task
        $signature = uniqid();
        $active_url = 'http://' . 
            $this->input->server('SERVER_NAME') . ':' .
            $this->input->server('SERVER_PORT'). '/user/active/load?' .
            http_build_query(array(
                'signature' => $signature
            ));
        $this->db->insert('find_user_password', array(
            'u_id' => $u_id,
            'signature' => $signature,
            'expire_dateline' => $current_dateline + 60 * 60 * 24 * 3
        ));

        //------ Send active email to user begin ----------
        $title = '欢迎您加入月田';
        $message = '请点击链接：<a href="'.$active_url.'">'.$active_url.'</a>激活帐号';
        $this->db->insert('email', array(
            'u_id' => $this->session->userdata['uid'],
            'title' => $title,
            'message' => $message,
            'dateline' => $current_dateline,
            'status' => OA_CONST_MESSAGE::STATUS_INIT,
        ));
        $email_id = $this->db->insert_id();

        $this->db->insert('email_address', array(
            'email_id' => $email_id,
            'u_id' => $u_id,
            'address' => $safe_vars['email'],
            'status' => OA_CONST_MESSAGE::STATUS_INIT,
        ));
        $this->db->trans_complete();

        /*
        // Send email, If failed, this mail will be sended
        // by email daemon
        $this->load->library('email');
        $this->email->from('leikou@163.com');
        $this->email->to($safe_vars['email']);
        $this->email->subject($title);
        $this->email->message($message);
    
        if($this->email->send())
        {
            $this->db->trans_start();

            $this->db->where('id', $email_id)->update('email', array(
                'status' => OA_CONST_MESSAGE::STATUS_DONE,
            ));

            $this->db->where('email_id', $email_id)->update('email_address', array(
                'status' => OA_CONST_MESSAGE::STATUS_DONE,
                'send_dateline' => $current_dateline,
            ));

            $this->db->trans_complete();
        }
        */

        //------------ Sent active email to user end --------------

        $this->load->view('info', array(
            'message' => '添加帐号: ' . $safe_vars['name'] . "($u_id)成功",
            'url' => $safe_vars['return_url'],
        ));
    }


    /**
     * @name 用户详细信息
     * @desc 权限模块，用户详细信息展示
     */
    public function user_detail()
    {
        //------------- check user input begin -------------
        list($safe_vars) = $this->check(array(
            'u_id' => FC_int('用户工号')->required(),
        ));

        // logic check
        $query = $this->db
            ->from('user')
            ->where('id', $safe_vars['u_id'])
            ->where('status', OA_CONST_USER::STATUS_NORMAL)
            ->get();
        $user = $query->first_row('array');
        if(empty($user))
        {
            show_error('您要查看的用户不存在');
        }
        //------------- check user input end ---------------

        // Get department
        $query = $this->db->from('department')->get();
        $department_info = $query->result_array();
        
        // Get role
        $role_where = array();
        if( ! $this->session->is_master())
        {
            $role_where = array(
                'catagory_id <>' => OA_CONST_CATAGORY::PERMISSION,
            );
        }

        $role_dict = $this->_get_role_dict($role_where);

        // Get catagory
        $catagory_dict = $this->_get_catagroy_dict();

        // Get user role
        $query = $this->db
            ->select('r.id, r.catagory_id')
            ->from('user_role AS u')
            ->join('role AS r', 'u.r_id = r.id')
            ->where('u_id', $user['id'])
            ->get();
        $user_role = $query->result_array();
        $user_role_list = array();
        foreach($user_role as $item)
        {
            if(
                ! $this->session->is_master() && 
                $item['catagory_id'] == OA_CONST_CATAGORY::PERMISSION
            )
            {
                show_error('您无权查看该用户');
            }
            $user_role_list[] = $item['id'];
        }

        $this->load->view('user_detail', array(
            'department_info' => $department_info,
            'role_dict' => $role_dict,
            'catagory_dict' => $catagory_dict,
            'user' => $user,
            'user_role_list' => $user_role_list,
            'perm_catagory_id' => OA_CONST_CATAGORY::PERMISSION,
            'gender_setting' => OA_CONST_USER::$GENDER,
            'return_url' => $this->agent->referrer(),
            'token_name' => $this->security->get_csrf_token_name(),
            'token_hash' => $this->security->get_csrf_hash(),
        ));
    }


    /**
     * @name 编辑用户
     * @desc 权限模块，编辑用户信息
     * @method post
     */
    public function user_edit()
    {
        //----------- check user input begin --------------
        list($safe_vars) = $this->check(array(
            'u_id' => FC_int('用户工号')->required(),
            'email' => FC_email('邮件地址')->max(64)->required(),
            'birthday' => FC_str('生日', '0000-00-00')
                ->re('/^\d{4}-\d{2}-\d{2}$/')->required(),
            'gender' => FC_int('性别')->callback(function($v) {
                $valid = ($v === NULL || array_key_exists($v, OA_CONST_USER::$GENDER))
                    ? TRUE : FALSE;
                return array($valid, $v);
            }),
            'department_id' => FC_int('部门')->required(),
            'user_role' => FC_int('用户权限')->multi()->required(),
            'return_url' => FC_str('返回地址', '')->max(255),
        ));

        // Check department
        $query = $this->db
            ->from('department')
            ->where('id', $safe_vars['department_id'])
            ->get();
        if($query->num_rows() != 1)
        {
            show_error('您提交的部门不存在');
        }

        // Check user
        $query = $this->db
            ->from('user')
            ->where('id', $safe_vars['u_id'])
            ->get();
        if($query->num_rows() != 1)
        {
            show_error('你要编辑的用户不存在');
        }

        // Check user role
        list($is_valid, $error) = $this->_check_user_role($safe_vars['user_role']);
        if( ! $is_valid)
        {
            show_error($error);
        }
        //----------- check user input end ----------------
        
        // Only maser has right to edit perm user
        $query = $this->db
            ->select('COUNT(*) AS count')
            ->from('user_role AS u')
            ->join('role AS r', 'u.r_id = r.id')
            ->where('u_id', $safe_vars['u_id'])
            ->where('r.catagory_id', OA_CONST_CATAGORY::PERMISSION)
            ->get();
        $role_catagory_info = $query->first_row('array');
        if(
            ! $this->session->is_master() && 
            $role_catagory_info['count']
        )
        {
            show_error('您无权编辑该用户');
        }
        
        $this->db->trans_start();
        
        $this->db->where('id', $safe_vars['u_id'])->update('user', array(
            'email' => $safe_vars['email'],
            'birthday' => $safe_vars['birthday'],
            'gender' => $safe_vars['gender'],
            'department_id' => $safe_vars['department_id'],
        ));

        // update user role
        $this->db->where('u_id', $safe_vars['u_id'])->delete('user_role'); 
        $insert_data = array();
        foreach($safe_vars['user_role'] as $r_id)
        {
            $insert_data[] = array(
                'u_id' => $safe_vars['u_id'],
                'r_id' => $r_id,
            );
        }
        $this->db->insert_batch('user_role', $insert_data);
        $this->db->trans_complete();

        $this->load->view('info', array(
            'message' => '编辑用户成功',
            'url' => $safe_vars['return_url'],
        ));
    }


    /*-----------------------------------------------------
     * --------  common util function ------------
     * ----------------------------------------------------/
     

    /*
     * product catagory associate array
     */
    private function _get_catagroy_dict()
    {
        $query = $this->db->from('catagory')->get();
        $catagory_info = $query->result_array();
        $query->free_result();

        $catagory_dict = array();
        foreach($catagory_info as $info)
        {
            $catagory_dict[$info['id']] = $info['title'];
        }

        return $catagory_dict;
    }


    /*
     * product role associate array
     */
    private function _get_role_dict($where_array = array())
    {
        $table_obj = $this->db->from('role');
        if( ! empty($where_array))
        {
            $table_obj->where($where_array);
        }
        $query = $table_obj->get();

        $role_info = $query->result_array();
        $query->free_result();

        $role_dict = array();
        foreach($role_info as $info)
        {
            $role_dict[$info['catagory_id']][] = $info;
        }

        return $role_dict;
    }


    /*
     * Check user role.
     * If user has perm role, this user can not be set other role, vice versa.
     */
    private function _check_user_role($user_role_list)
    {
        $query = $this->db
            ->select('DISTINCT catagory_id', FALSE)
            ->from('role')
            ->where_in('id', $user_role_list)
            ->get();

        $catagory_info = $query->result_array();
        $catagory_list = array();
        foreach($catagory_info as $item)
        {
            $catagory_list[] = $item['catagory_id'];
        }

        if(count($catagory_list) != count($user_role_list))
        {
            return array(FALSE, '您提交的权限非法');
        }

        if(
            count($catagory_list) > 1 && 
            in_array(OA_CONST_CATAGORY::PERMISSION, $catagory_list)
        )
        {
            return array(FALSE, '设置管理权限时，不能同时设置其它权限');
        }

        return array(TRUE, NULL);
    }
}

/* End of file: user.php */
/* Location: ./application/controllers/user.php */
